package com.cgs.query.connection

import com.cgs.query.domain.QuerySource
import com.cgs.query.exception.QueryException
import com.cgs.query.service.IQueryProjectService
import mu.KotlinLogging
import java.sql.Connection
import java.sql.DriverManager
import java.sql.SQLException
import java.util.*

private val logger = KotlinLogging.logger { }

/**
 *默认读取define中定义的DataSource
 */
class DefaultConnectionFactory(private val queryProjectService: IQueryProjectService) : ConnectionFactory {

    override fun getConnection(querySource: QuerySource): Connection {
        return getConnectionWithSource(querySource);
    }

    override fun getConnection(projectName: String): Connection {
        return getConnectionWithSource(queryProjectService.findSourceByName(projectName)
                ?: throw QueryException("找不到数据源,项目[$projectName]")).apply { logger.debug { "得到连接[${this}]" } }
    }

    override fun returnConnection(conn: Connection) = conn.close()

    companion object {

        fun getConnectionWithSource(querySource: QuerySource): Connection {
            if (querySource.url.isBlank())
                throw QueryException("连接信息[Url]不能为空")

            val p = Properties().apply {
                this.setProperty("user", querySource.userName)
                this.setProperty("password", querySource.password)
            }

            val connection: Connection?
            try {
                connection = DriverManager.getConnection(querySource.url, p)
            } catch (e: SQLException) {
                throw QueryException("获取数据库连接失败[${querySource.url}]", e)
            }
            return connection
                    ?: throw QueryException("获取数据库链接失败[${querySource.url}]").apply { logger.error { "数据库驱动异常,获得空连接[${querySource.url}]" } }
        }
    }

}
